package org.eden.rpc.core.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.eden.rpc.common.entity.RpcRequest;
import org.eden.rpc.common.entity.RpcResponse;
import org.eden.rpc.common.enumerate.PackageType;

public class DefaultEncoder<I> extends MessageToByteEncoder<I> {

    private static final int MAGIC_NUMBER = 0xCAFEBABE;

    private final Serializer serializer;

    public DefaultEncoder(Serializer serializer, Class<? extends I> clazz) {
        super(clazz);
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, I msg, ByteBuf out) throws Exception {
        out.writeInt(MAGIC_NUMBER);
        if (msg instanceof RpcRequest) {
            out.writeInt(PackageType.REQUEST_PACKAGE.getType());
        } else if (msg instanceof RpcResponse) {
            out.writeInt(PackageType.RESPONSE_PACKAGE.getType());
        }
        out.writeInt(serializer.getCode());
        byte[] bytes = serializer.serialize(msg);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
    }
}
